<?php
/**
 * Created by PhpStorm.
 * User: zhangyi
 * Date: 17/3/12
 * Time: 上午12:52
 */
namespace backend\components;

use app\models\CaptchaLog;
use app\models\Member;
use Yii;
use yii\web\Response;

class CustomAction extends \yii\captcha\CaptchaAction
{
    private $message = '操作成功';
    private $status = 1;
    private $content;
    private $picurl;

    public $imageLibrary='imagick';
    private $_originData;//源数据


    public function run()
    {
        $this->_originData = file_get_contents("php://input");
        $this->_originData = json_decode($this->_originData,true);

        $mobile = $this->_originData['mobile'];
        $action = $this->_originData['action'];
        if($this->verifyMobileValid($mobile)) {
            $code = $this->getVerifyCode(true);
            $model = CaptchaLog::findOne(['mobile'=>$mobile,'action'=>$action]);
            if(empty($model)) {
                $model = new CaptchaLog();
                $model->mobile = $mobile;
                $model->action = $action;
            }
            $model->code = $code;

            if($model->save()) {
                $this->content = array('url'=>$this->renderImage($code));
            } else {
                $this->status = -1;
                $this->message = '操作失败';
            }
            $this->generateNewMember();
        } else {
            $this->status = -1;
            $this->message = '手机号码格式错误';
        }

        return $this->outputJson();

    }
    private function outputJson()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        Yii::$app->response->data = array(
            'header'=>array(
                'status'=>$this->status,
                'message'=>$this->message,
            ),
            'content'=>$this->content,
        );
        Yii::$app->end();
    }
    //检查手机号码有效性
    protected function verifyMobileValid($mobile)
    {
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }

    protected function renderImageByImagick($code)
    {
        $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
        $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));

        $image = new \Imagick();
        $image->newImage($this->width, $this->height, $backColor);

        $draw = new \ImagickDraw();
        $draw->setFont($this->fontFile);
        $draw->setFontSize(30);
        $fontMetrics = $image->queryFontMetrics($draw, $code);

        $length = strlen($code);
        $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
        $h = (int) $fontMetrics['textHeight'] - 8;
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $draw = new \ImagickDraw();
            $draw->setFont($this->fontFile);
            $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8));
            $draw->setFillColor($foreColor);
            $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]);
            $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
            $x += (int) $fontMetrics['textWidth'] + $this->offset;
        }

        $image->setImageFormat('png');
        $file = $this->generateFilePath();
        $image->writeImage($file);

        return str_replace(Yii::getAlias('@webroot'),Yii::$app->request->hostInfo,$file);
    }
    private function generateFilePath()
    {
        $dir = Yii::getAlias('@webroot/uploads/captcha').date("Ymd");
        if(!file_exists($dir)) {
            mkdir($dir,0777,1);
        }
        $time = time();
        $filename = $time.'.png';
        while(file_exists($dir.'/'.$filename)) {
            $filename = $time.'_'.rand(1000,9999).'.png';
        }
        return $dir.'/'.$filename;

    }
    private function generateNewMember()
    {
        $model = Member::find()->where(['mobile'=>$this->_originData['mobile']])->one();
        if(empty($model)) {
            $model = new Member();
            $model->mobile = $this->_originData['mobile'];
            $model->channel = $this->_originData['channel'];
            $model->product = $this->_originData['product'];
            $model->save();
        }

    }

    /**
     * Generates a new verification code.
     * @return string the generated verification code
     */
    protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 20) {
            $this->maxLength = 20;
        }
        $length = mt_rand($this->minLength, $this->maxLength);

        $letters = '987654321098765432109';
        $vowels = '13579';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
                $code .= $vowels[mt_rand(0, 4)];
            } else {
                $code .= $letters[mt_rand(0, 20)];
            }
        }

        return $code;
    }
}